package com.minstone.common.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.log4j.Logger;

import com.minstone.common.bean.ResultBean;
import com.minstone.common.util.WebUtil;

/**
 * 对请求进行过滤
 * @author vic
 *
 */
public class CommonServiceRequestFilter implements Filter {
	
	private static final Logger LOGGER = Logger.getLogger(CommonServiceRequestFilter.class);

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		neverBug();
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		try {
			chain.doFilter(request, response);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
			responseExceptionJson(response);
		} finally{
			printParams(request);
		}
	}

	/**
	 * 接口参数打印
	 * @param request
	 */
	private void printParams(ServletRequest request) {
		//获取调用接口所传参数
		Map map = WebUtil.getParamMap(request);
		System.out.println("接口接收到的参数打印：start");
		for (Object obj : map.keySet()) {
			System.out.println(obj+":"+map.get(obj));
		}
		System.out.println("接口接收到的参数打印：end");
	}

	/**
	 * 接口调用异常后响应
	 * @param response
	 * @throws IOException
	 */
	private void responseExceptionJson(ServletResponse response)
			throws IOException {
		//拼接返回参数
		ResultBean resultBean = new ResultBean();
		resultBean.setStatus("500");
		resultBean.setDesc("服务器内部异常");
		//将数据写回页面
		responseJson(response, resultBean);
	}

	/**
	 * 响应json数据
	 * @param response
	 * @param resultBean
	 * @throws IOException
	 */
	private void responseJson(ServletResponse response, ResultBean resultBean)
			throws IOException {
		response.setContentType("application/json;charset=utf-8");
		PrintWriter writer = response.getWriter();
		writer.write(resultBean.toJson());
	}

	@Override
	public void destroy() {
		Enumeration<Driver> drivers = DriverManager.getDrivers();
		try {
			if (drivers != null) {
				while (drivers.hasMoreElements()) {
					DriverManager.deregisterDriver(drivers.nextElement());
				}
			}
		} catch (SQLException e) {
			LOGGER.error("关闭jdbc注册错误!", e);
		}
		System.out.println("过滤器销毁");
	}
	
	public static void neverBug() {
		String str = ""+
			 "                               _ooOoo_                           \n"+
			 "                              o8888888o                          \n"+
			 "                              88\" . \"88                        \n  "+
			 "                            (| -_- |)                          \n"+
			 "                              O\\  =  /O                         \n "+
			 "                          ____/`---'\\____                      \n "+
			 "                        .'  \\\\|     |//  `.                   \n  "+
			 "                      /  \\\\|||  :  |||//  \\                 \n   "+
			 "                    /  _||||| -:- |||||-  \\                  \n "+
			 "                      |   | \\\\\\  -  /// |   |                \n   "+
			 "                    | \\_|  ''\\---/''  |   |                 \n  "+
			 "                     \\  .-\\__  `-`  ___/-. /                 \n  "+
			 "                    __`. .'  /--.--\\  `. . __                 \n "+
			 "                  .\"\"'<  `.___\\_<|>_/___.'  >'\"\".          \n     "+
			 "            | | :  `- \\`.;`\\ _ /`;.`/ - ` : | |           \n  "+
			 "               \\  \\ `-.   \\_ __\\ /__ _/   .-` /  /         \n    "+
			 "        ======`-.____`-.___\\_____/___.-`____.-'======       \n "+
			 "                              `=---='                           \n"+
			 "            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^        \n"+
			 " ===========================佛祖保佑       永无bug===========================\n";
		System.out.println(str);
	}
}
